package cn.play.cardgame.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.play.cardgame.MainActivity;
import cn.play.cardgame.R;
import cn.play.cardgame.bean.BetItem;
import cn.play.cardgame.bean.MachineSet;
import cn.play.cardgame.bean.PaiItem;
import cn.play.cardgame.bean.ValueItem;
import cn.play.cardgame.constant.Constant;
import cn.play.cardgame.data.ErrorData;
import cn.play.cardgame.data.FaPai;
import cn.play.cardgame.data.ModifyBetData;
import cn.play.cardgame.data.ValueData;
import cn.play.cardgame.event.CallbackEvent;
import cn.play.cardgame.util.CryptUtils;
import cn.play.cardgame.util.ImageUtil;
import cn.play.cardgame.util.LogUtil;
import cn.play.cardgame.util.SharePreferenceUtil;
import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class BetPanel extends LinearLayout {
    private static final String BET_HS_HEITAO = "S";
    private static final String BET_HS_HONGTAO = "H";
    private static final String BET_HS_MIEHUA = "C";
    private static final String BET_HS_FANGKUAI = "D";
    private static final String BET_HS_KING = "O";

    private Map<String, String> sendHsMap = new HashMap<>();

    @InjectView(R.id.bet_heitao_panel)
    ImageView mBetHeitaoPanel;
    @InjectView(R.id.bet_hongtao_panel)
    ImageView mBetHongtaoPanel;
    @InjectView(R.id.bet_caohua_panel)
    ImageView mBetCaohuaPanel;
    @InjectView(R.id.bet_fangkuai_panel)
    ImageView mBetFangkuaiPanel;
    @InjectView(R.id.bet_king_panel)
    ImageView mBetKingPanel;

    @InjectView(R.id.bet_heitao_mine)
    ImageView mBetHeitaoMine;
    @InjectView(R.id.bet_hongtao_mine)
    ImageView mBetHongtaoMine;
    @InjectView(R.id.bet_caohua_mine)
    ImageView mBetCaohuaMine;
    @InjectView(R.id.bet_fangkuai_mine)
    ImageView mBetFangkuaiMine;
    @InjectView(R.id.bet_king_mine)
    ImageView mBetKingMine;
    @InjectView(R.id.machine_position)
    ImageView machinePos;
    @InjectView(R.id.bet_king_ratio)
    ImageView mKingRatio;

    @InjectView(R.id.bet_heitao_guang)
    ImageView mHeitaoGuang;
    @InjectView(R.id.bet_hongtao_guang)
    ImageView mHongtaoGuang;
    @InjectView(R.id.bet_caohua_guang)
    ImageView mCaohuaGuang;
    @InjectView(R.id.bet_fangkuai_guang)
    ImageView mFangkuaiGuang;
    @InjectView(R.id.bet_king_guang)
    ImageView mKingGuang;

    private int Mine_A = 0;
    private int Mine_B = 0;
    private int Mine_C = 0;
    private int Mine_D = 0;
    private int Mine_E = 0;

    private float multi_A = 3.8f;
    private float multi_B = 3.8f;
    private float multi_C = 4.0f;
    private float multi_D = 4.0f;
    private float multi_E = 20.0f;

    private float balance = 0f;
    private int step = 5;
    private float app_current_profit = 0f;
    // private int server_current_profit = 0;

    private Context mContext;
    private ImageView currentSelected;
    private MachineSet machineSet;
    private boolean isHighlightEnabled = false;

    private boolean lockLongPressKeyHeitao = false;
    private boolean lockLongPressKeyHongtao = false;
    private boolean lockLongPressKeyCaohua = false;
    private boolean lockLongPressKeyFangkuai = false;
    private boolean lockLongPressKeyKing = false;

    private boolean isMineBetVisible = true;

    private Handler handler2;
    private boolean isStop = false;
    private int mViewIndex = 0;

    public BetPanel(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        initData();
        initViews();
        initListener();
        initHandler();
    }

    public BetPanel(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BetPanel(Context context) {
        this(context, null);
    }

    private void initData() {
        startThreads();
    }

    private void initViews() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        View view = View.inflate(mContext, R.layout.bet_panel, null);
        ButterKnife.inject(this, view);
        this.addView(view, params);
    }

    private void initListener() {
//        mBetHeitaoPanel.setOnClickListener(this);
//        mBetHongtaoPanel.setOnClickListener(this);
//        mBetCaohuaPanel.setOnClickListener(this);
//        mBetFangkuaiPanel.setOnClickListener(this);
//        mBetKingPanel.setOnClickListener(this);

//		 mBetHeitaoPanel.setOnKeyListener(this);
//		 mBetHongtaoPanel.setOnKeyListener(this);
//		 mBetCaohuaPanel.setOnKeyListener(this);
//		 mBetFangkuaiPanel.setOnKeyListener(this);
//		 mBetKingPanel.setOnKeyListener(this);
        clearMineBet();
    }

    private void clearSelectedState() {
        if (isHighlightEnabled) {
            mBetHeitaoPanel.setImageResource(R.drawable.action_btn_select0);
            mBetHongtaoPanel.setImageResource(R.drawable.action_btn_select1);
            mBetCaohuaPanel.setImageResource(R.drawable.action_btn_select2);
            mBetFangkuaiPanel.setImageResource(R.drawable.action_btn_select3);
            mBetKingPanel.setImageResource(R.drawable.action_btn_select4);
            mViewIndex = -1;

            isStop = false;
            visibleAll(1, false);
        } else {
            mBetHeitaoPanel.setImageResource(R.drawable.action_btn_normal0);
            mBetHongtaoPanel.setImageResource(R.drawable.action_btn_normal1);
            mBetCaohuaPanel.setImageResource(R.drawable.action_btn_normal2);
            mBetFangkuaiPanel.setImageResource(R.drawable.action_btn_normal3);
            mBetKingPanel.setImageResource(R.drawable.action_btn_normal4);
            mViewIndex = -1;
            isStop = true;
            visibleAll(1, false);
        }

    }

    public boolean getIsButtonHighlighted() {
        return isHighlightEnabled;
    }

    public void setButtonEnabled(boolean isHighlightEnabled) {
        this.isHighlightEnabled = isHighlightEnabled;
        clearSelectedState();
    }

    public void setKingRatio() {
        multi_E = Constant.KING_RATIO;
        mKingRatio.setBackgroundDrawable(ImageUtil.getInstance().bitmapToDrawable(mContext,
                ImageUtil.getRatioMapping(), String.valueOf(Constant.KING_RATIO)));
    }

    private void startThreads() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (lockLongPressKeyHeitao) {
                    addBet("S");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (lockLongPressKeyHongtao) {
                    addBet("H");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (lockLongPressKeyCaohua) {
                    addBet("C");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (lockLongPressKeyFangkuai) {
                    addBet("D");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (lockLongPressKeyKing) {
                    addBet("O");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public boolean isLockLongPressKeyHeitao() {
        return lockLongPressKeyHeitao;
    }

    public void setLockLongPressKeyHeitao(boolean lockLongPressKeyHeitao) {
        this.lockLongPressKeyHeitao = lockLongPressKeyHeitao;
    }

    public boolean isLockLongPressKeyHongtao() {
        return lockLongPressKeyHongtao;
    }

    public void setLockLongPressKeyHongtao(boolean lockLongPressKeyHongtao) {
        this.lockLongPressKeyHongtao = lockLongPressKeyHongtao;
    }

    public boolean isLockLongPressKeyCaohua() {
        return lockLongPressKeyCaohua;
    }

    public void setLockLongPressKeyCaohua(boolean lockLongPressKeyCaohua) {
        this.lockLongPressKeyCaohua = lockLongPressKeyCaohua;
    }

    public boolean isLockLongPressKeyFangkuai() {
        return lockLongPressKeyFangkuai;
    }

    public void setLockLongPressKeyFangkuai(boolean lockLongPressKeyFangkuai) {
        this.lockLongPressKeyFangkuai = lockLongPressKeyFangkuai;
    }

    public boolean isLockLongPressKeyKing() {
        return lockLongPressKeyKing;
    }

    public void setLockLongPressKeyKing(boolean lockLongPressKeyKing) {
        this.lockLongPressKeyKing = lockLongPressKeyKing;
    }

    // private void showQCodeDialog() {
    // EventBus.getDefault().post(new
    // CallbackEvent(Constant.EVENT_NOTIFY_SHOW_CODE, ""));
    // }

    // 暂时模拟取消，测完注释掉
//    @OnClick(R.id.machine_pos_panel)
//    public void clickCancelBet(View view) {
//        // // cancelBet();
//        // // showQCodeDialog();
//        // addValue();
//        addBet("S");
//        addBet("H");
//        addBet("C");
//        addBet("D");
//        addBet("O");
//        // // returnValue(100);
//        // // setMineBetVisible();
//    }

    public void addBet(String huase) {
        //        if (balance < step) {
//            Toast.makeText(mContext, "余额不足，请充值", Toast.LENGTH_SHORT).show();
//            return;
//        }
        synchronized (this) {
            float mStep = step;
            // 余额小于step，没法押注，包括保存也不能

            LogUtil.getLogger().d7("07281000", "  balance = =====     " + balance);
            LogUtil.getLogger().d7("07281000", "  step = =====     " + step);

            if (balance < step) {
                if (balance == 0) {
                    Toast.makeText(mContext, "余额不足，请充值", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    mStep = balance;
                }
            } else {
                mStep = step;
            }

            if (isExistHuase(huase)) {
                addSendMap(huase);
                int A = Mine_A;
                int B = Mine_B;
                int C = Mine_C;
                int D = Mine_D;
                int E = Mine_E;

                int currentStep = 0;
                if (huase.equals("S")) {
                    int tempA = A;
                    A += mStep;
                    if (!isValidHeitao(A, B, C, D)) {
                        A = (Constant.FOUR_RED_LIMIT + B + C + D) / 3;
                    }
                    currentStep = A - tempA;
                } else if (huase.equals("H")) {
                    int tempB = B;
                    B += mStep;
                    if (!isValidHongtao(A, B, C, D)) {
                        B = (Constant.FOUR_RED_LIMIT + A + C + D) / 3;
                    }
                    currentStep = B - tempB;
                } else if (huase.equals("C")) {
                    int temp_C = C;
                    C += mStep;
                    if (!isValidCaohua(A, B, C, D)) {
                        C = (Constant.FOUR_RED_LIMIT + A + B + D) / 3;
                    }
                    currentStep = C - temp_C;
                } else if (huase.equals("D")) {
                    int temp_D = D;
                    D += mStep;
                    if (!isValidFangkuai(A, B, C, D)) {
                        D = (Constant.FOUR_RED_LIMIT + A + B + C) / 3;
                    }
                    currentStep = D - temp_D;
                } else if (huase.equals("O")) {
                    int temp_E = E;
                    E += mStep;
                    if (!isValidKing(E)) {
                        E = Constant.KING_RED_LIMIT;
                    }
                    currentStep = E - temp_E;
                }
                // Toast.makeText(mContext, "color:" + huase + ",step:" + step,
                // Toast.LENGTH_SHORT).show();
                Map<String, Object> map = new HashMap<>();
                map.put("rounds", String.valueOf(Constant.TURN));
                map.put("bouts", String.valueOf(Constant.BUREAU));
                map.put("value", String.valueOf(currentStep));
                map.put("color", huase);
                map.put("position", String.valueOf(Constant.POSITION));
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("position", Constant.POSITION);
                    jsonObject.put("token", FaPai.authentication(map));
                    jsonObject.put("value", mStep);
                    jsonObject.put("color", huase);
                    jsonObject.put("rounds", Constant.TURN);
                    jsonObject.put("bouts", Constant.BUREAU);
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                LogUtil.getLogger().d7("07281000", "       ");
                LogUtil.getLogger().d7("07281000", "       ");
                LogUtil.getLogger().d7("07281000", "押分请求花色:" + huase);
                LogUtil.getLogger().d7("07281000", "押分请求:" + jsonObject.toString());
                LogUtil.getLogger().d2("choice 加密前:" + jsonObject.toString());
                LogUtil.getLogger().d2("Constant.MACHINE_UPDATE_STAKE = " + Constant.MACHINE_UPDATE_STAKE);
                LogUtil.getLogger().d2("Constant.KEY_MACHINE_ID = " + Constant.KEY_MACHINE_ID);
                LogUtil.getLogger().d2("Constant.MACHINE_ID = " + Constant.MACHINE_ID);
                LogUtil.getLogger().d2("choice 加密后:"
                        + CryptUtils.encryptAES(jsonObject.toString(),
                        Constant.AES_KEY));
                OkHttpUtils
                        .post()
                        .url(Constant.MACHINE_UPDATE_STAKE)
                        .addParams(
                                "param",
                                CryptUtils.encryptAES(jsonObject.toString(),
                                        Constant.AES_KEY)).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(1).build()
                        .execute(new MyStringCallback(huase));
            } else {
//            Toast.makeText(mContext, "押分还没有返回，请稍候", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 取消本局押分
    public void cancelBet() {
        Map<String, Object> map = new HashMap<>();
        map.put("rounds", String.valueOf(Constant.TURN));
        map.put("bouts", String.valueOf(Constant.BUREAU));
        map.put("position", String.valueOf(Constant.POSITION));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("position", Constant.POSITION);
            jsonObject.put("token", FaPai.authentication(map));
            jsonObject.put("bouts", Constant.BUREAU);
            jsonObject.put("rounds", Constant.TURN);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        LogUtil.getLogger().d("choice  取消加密前:" + jsonObject.toString());
        LogUtil.getLogger().d("choice  取消加密后:"
                + CryptUtils.encryptAES(jsonObject.toString(),
                Constant.AES_KEY));
        OkHttpUtils
                .post()
                .url(Constant.CANCEL_STAKE)
                .addParams(
                        "param",
                        CryptUtils.encryptAES(jsonObject.toString(),
                                Constant.AES_KEY))
                .addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(6).build()
                .execute(new MyStringCallback());
    }

    // 加值
    public void addValue() {
        Map<String, Object> map = new HashMap<>();
        map.put("position", String.valueOf(Constant.POSITION));
        map.put("value", String.valueOf(step));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("position", Constant.POSITION);
            jsonObject.put("token", FaPai.authentication(map));
            jsonObject.put("value", step);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        LogUtil.getLogger().d("上分：");
        LogUtil.getLogger().d("加密前：" + jsonObject.toString());
        LogUtil.getLogger().d("加密前：" + CryptUtils.encryptAES(jsonObject.toString(), Constant.AES_KEY));
        OkHttpUtils
                .post()
                .url(Constant.ADD_VALUE)
                .addParams(
                        "param",
                        CryptUtils.encryptAES(jsonObject.toString(),
                                Constant.AES_KEY)).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(4).build()
                .execute(new MyStringCallback());

//        OkHttpUtils
//                .post()
//                .url(Constant.ADD_VALUE)
//                .addParams(
//                        "param",
//                        jsonObject.toString()).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(4).build()
//                .execute(new MyStringCallback());
    }

    // 退值
    public void returnValue() {
        Map<String, Object> map = new HashMap<>();
        map.put("position", String.valueOf(Constant.POSITION));
        map.put("value", String.valueOf(step));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("position", Constant.POSITION);
            jsonObject.put("token", FaPai.authentication(map));
            jsonObject.put("value", step);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        LogUtil.getLogger().d2("下分：");
        LogUtil.getLogger().d2("加密前：" + jsonObject.toString());
        LogUtil.getLogger().d2("加密前：" + CryptUtils.encryptAES(jsonObject.toString(), Constant.AES_KEY));
        LogUtil.getLogger().d2("Constant.RETURN_VALUE：" + Constant.RETURN_VALUE);
        LogUtil.getLogger().d2("Constant.KEY_MACHINE_ID：" + Constant.KEY_MACHINE_ID);
        LogUtil.getLogger().d2("Constant.MACHINE_ID：" + Constant.MACHINE_ID);
        OkHttpUtils
                .post()
                .url(Constant.RETURN_VALUE)
                .addParams(
                        "param",
                        CryptUtils.encryptAES(jsonObject.toString(),
                                Constant.AES_KEY)).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(4).build()
                .execute(new MyStringCallback());

//        OkHttpUtils
//                .post()
//                .url(Constant.RETURN_VALUE)
//                .addParams(
//                        "param",
//                        jsonObject.toString()).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(4).build()
//                .execute(new MyStringCallback());
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        return super.onKeyMultiple(keyCode, repeatCount, event);
    }

    public void setMineBetVisible() {
        isMineBetVisible = !isMineBetVisible;
        if (isMineBetVisible) {
            mBetHeitaoMine.setVisibility(View.VISIBLE);
            mBetHongtaoMine.setVisibility(View.VISIBLE);
            mBetCaohuaMine.setVisibility(View.VISIBLE);
            mBetFangkuaiMine.setVisibility(View.VISIBLE);
            mBetKingMine.setVisibility(View.VISIBLE);
        } else {
            mBetHeitaoMine.setVisibility(View.INVISIBLE);
            mBetHongtaoMine.setVisibility(View.INVISIBLE);
            mBetCaohuaMine.setVisibility(View.INVISIBLE);
            mBetFangkuaiMine.setVisibility(View.INVISIBLE);
            mBetKingMine.setVisibility(View.INVISIBLE);
        }
    }

//    @Override
//    public void onClick(View v) {
//        if (!isHighlightEnabled)
//            return;
////        if (balance < step) {
////            Toast.makeText(mContext, "余额不足，请充值", Toast.LENGTH_SHORT).show();
////            return;
////        }
//        currentSelected = null;
//        switch (v.getId()) {
//            case R.id.bet_heitao_panel:
//                currentSelected = mBetHeitaoPanel;
//                break;
//            case R.id.bet_hongtao_panel:
//                currentSelected = mBetHongtaoPanel;
//                break;
//            case R.id.bet_caohua_panel:
//                currentSelected = mBetCaohuaPanel;
//                break;
//            case R.id.bet_fangkuai_panel:
//                currentSelected = mBetFangkuaiPanel;
//                break;
//            case R.id.bet_king_panel:
//                currentSelected = mBetKingPanel;
//                break;
//        }
////        addBet(getBetHuase());
//        EventBus.getDefault().post(
//                new CallbackEvent(Constant.EVENT_NOTIFY_PREPARE_TO_BET,
//                        getBetHuase()));
//    }

    private String getBetHuase() {
        if (currentSelected == mBetHeitaoPanel) {
            return "S";
        } else if (currentSelected == mBetHongtaoPanel) {
            return "H";
        } else if (currentSelected == mBetCaohuaPanel) {
            return "C";
        } else if (currentSelected == mBetFangkuaiPanel) {
            return "D";
        } else if (currentSelected == mBetKingPanel) {
            return "O";
        }
        return null;
    }

    public void setHighLight(PaiItem paiBean) {
        isStop = false;
        if (FaPai.isHeixin(paiBean.getPaiHuase())) {
            mViewIndex = 0;
            mBetHeitaoPanel.setImageResource(R.drawable.action_btn_select0);
        } else if (FaPai.isHongxin(paiBean.getPaiHuase())) {
            mViewIndex = 1;
            mBetHongtaoPanel.setImageResource(R.drawable.action_btn_select1);
        } else if (FaPai.isFangkuai(paiBean.getPaiHuase())) {
            mViewIndex = 3;
            mBetFangkuaiPanel.setImageResource(R.drawable.action_btn_select3);
        } else if (FaPai.isCaohua(paiBean.getPaiHuase())) {
            mViewIndex = 2;
            mBetCaohuaPanel.setImageResource(R.drawable.action_btn_select2);
        } else if (FaPai.isKing(paiBean.getPaiHuase())) {
            mViewIndex = 4;
            mBetKingPanel.setImageResource(R.drawable.action_btn_select4);
        }
        visibleAll(1, true);
        calculate(paiBean);
    }

    private void calculate(PaiItem paiBean) {
        //暂时把这个日志去掉
//        LogUtil.getLogger().d2("paiBean.getPaiHuase()=<" + paiBean.getPaiHuase() + "> Mine_A=<" + Mine_A + ">  Mine_B=<" + Mine_B + "> Mine_C=<" + Mine_C + "> Mine_D =<" + Mine_D + "> Mine_E =<" + Mine_E + ">");
//        LogUtil.getLogger().d7("KING", "**************************************************** ");
//        LogUtil.getLogger().d7("KING", "Mine_A = " + Mine_A);
//        LogUtil.getLogger().d7("KING", "Mine_B = " + Mine_B);
//        LogUtil.getLogger().d7("KING", "Mine_C = " + Mine_C);
//        LogUtil.getLogger().d7("KING", "Mine_D = " + Mine_D);
//        LogUtil.getLogger().d7("KING", "Mine_D = " + Mine_E);
//        LogUtil.getLogger().d7("KING", "**************************************************** ");
        if (FaPai.isHeixin(paiBean.getPaiHuase())) {
            app_current_profit = multi_A * Mine_A;
            // server_current_profit = (int) (multi_A * Mine_A -
            // getMineBetAll());
            balance += app_current_profit;
        } else if (FaPai.isHongxin(paiBean.getPaiHuase())) {
            app_current_profit = multi_B * Mine_B;
            // server_current_profit = (int) (multi_B * Mine_B -
            // getMineBetAll());
            balance += app_current_profit;
        } else if (FaPai.isCaohua(paiBean.getPaiHuase())) {
            app_current_profit = multi_C * Mine_C;
            // server_current_profit = (int) (multi_C * Mine_C -
            // getMineBetAll());
            balance += app_current_profit;
        } else if (FaPai.isFangkuai(paiBean.getPaiHuase())) {
            app_current_profit = multi_D * Mine_D;
            // server_current_profit = (int) (multi_D * Mine_D -
            // getMineBetAll());
            balance += app_current_profit;
        } else if (FaPai.isKing(paiBean.getPaiHuase())) {
            app_current_profit = multi_E * Mine_E;
            // server_current_profit = (int) (multi_E * Mine_E - Mine_E);
            //中王后的退分
            balance = balance + app_current_profit + Mine_A + Mine_B + Mine_C
                    + Mine_D;
        }
    }


    public float getBalance() {
        return balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }

    public float getAppCurrentProfit() {
        return app_current_profit;
    }

    // public int getServerCurrentProfit() {
    // return server_current_profit;
    // }

    public void changeStep(int step) {
        this.step = step;
    }

    public int getStep() {
        return step;
    }

    public int getMineBetAll() {
        return Mine_A + Mine_B + Mine_C + Mine_D + Mine_E;
    }

    // 新的一局需要清零
    public void clearMineBet() {
        // 存入SharedPreference
        SharePreferenceUtil.putLastWin(mContext, app_current_profit);
        Mine_A = Mine_B = Mine_C = Mine_D = Mine_E = 0;
        app_current_profit = 0;
        setMineHeitaoBet();
        setMineHongtaoBet();
        setMineCaohuaBet();
        setMineFangkuaiBet();
        setMineKingBet();
    }

    public void setData(MachineSet machineSet) {
        this.machineSet = machineSet;
    }

    private int[] ids = {R.drawable.goldnum_1, R.drawable.goldnum_2,
            R.drawable.goldnum_3, R.drawable.goldnum_4, R.drawable.goldnum_5,
            R.drawable.goldnum_6, R.drawable.goldnum_7, R.drawable.goldnum_8, R.drawable.goldnum_0};

    private int getMachinePosImageId(int pos) {
        return ids[pos - 1];
    }

    public void setMachinePos(int pos) {
        machinePos.setBackgroundResource(getMachinePosImageId(pos));
    }

    private void setMineKingBet() {
        LogUtil.getLogger().d("bet    setMineKingBet");
        mBetKingMine.setBackgroundDrawable(ImageUtil.getInstance()
                .bitmapToDrawable(mContext, ImageUtil.getBetMapping(),
                        String.valueOf(Mine_E)));
    }

    private void setMineHeitaoBet() {
        Thread.dumpStack();
        LogUtil.getLogger().d("bet   setMineHeitaoBet");
        mBetHeitaoMine.setBackgroundDrawable(ImageUtil.getInstance()
                .bitmapToDrawable(mContext, ImageUtil.getBetMapping(),
                        String.valueOf(Mine_A)));
    }

    private void setMineHongtaoBet() {
//        Thread.dumpStack();
        mBetHongtaoMine.setBackgroundDrawable(ImageUtil.getInstance()
                .bitmapToDrawable(mContext, ImageUtil.getBetMapping(),
                        String.valueOf(Mine_B)));
    }

    private void setMineCaohuaBet() {
        Thread.dumpStack();
        mBetCaohuaMine.setBackgroundDrawable(ImageUtil.getInstance()
                .bitmapToDrawable(mContext, ImageUtil.getBetMapping(),
                        String.valueOf(Mine_C)));
    }

    private void setMineFangkuaiBet() {
        Thread.dumpStack();
        mBetFangkuaiMine.setBackgroundDrawable(ImageUtil.getInstance()
                .bitmapToDrawable(mContext, ImageUtil.getBetMapping(),
                        String.valueOf(Mine_D)));
    }

    private boolean isValidHeitao(int A, int B, int C, int D) {
        int M = A;
        if (M * 4 - (A + B + C + D) <= Constant.FOUR_RED_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isValidHongtao(int A, int B, int C, int D) {
        int M = B;
        if (M * 4 - (A + B + C + D) <= Constant.FOUR_RED_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isValidCaohua(int A, int B, int C, int D) {
        int M = C;
        if (M * 4 - (A + B + C + D) <= Constant.FOUR_RED_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isValidFangkuai(int A, int B, int C, int D) {
        int M = D;
        if (M * 4 - (A + B + C + D) <= Constant.FOUR_RED_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isValidKing(int E) {
        return E <= Constant.KING_RED_LIMIT;
    }

    public class MyStringCallback extends StringCallback {
        String huase;

        public MyStringCallback() {
        }

        public MyStringCallback(String huase) {
            this.huase = huase;
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            LogUtil.getLogger().d("NFCTAG  id = " + id + "<---exception_message-->" + e.getMessage());
        }

        @Override
        public void onResponse(String response, int id) {
            try {
                LogUtil.getLogger().d("NFCTAG" + "id = " + id + "<---response_message-->" + response);
                if (!TextUtils.isEmpty(response) && response.indexOf("code\":2") != -1) {
                    Gson gson = new Gson();
                    ErrorData mErrorData = gson.fromJson(response, ErrorData.class);
                    Toast.makeText(mContext, mErrorData.getResult(), Toast.LENGTH_SHORT).show();

                    return;
                }
                if (id == 1) {

                    removeSendMap(huase);

                    LogUtil.getLogger().d2("NFCTAG" + "id = " + id + "<---response_message-->" + response);
                    LogUtil.getLogger().d2("bethaha = " + response);
                    LogUtil.getLogger().d7("07281000", "押分返回:" + response);
                    Gson gson = new Gson();
                    ModifyBetData modifyBetData = gson.fromJson(response,
                            ModifyBetData.class);
                    if (!TextUtils.isEmpty(modifyBetData.getMsg())) {
                        Toast.makeText(mContext, modifyBetData.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    if (modifyBetData.getCode() == -1)
                        return;
                    BetItem item = modifyBetData.getResult();
                    int currentBet = item.getCurrentBet();
                    String color = item.getBetColor();

                    if (color.equals("S")) {
                        Mine_A = Mine_A + currentBet;
                        setMineHeitaoBet();
                    } else if (color.equals("H")) {
                        Mine_B = Mine_B + currentBet;
                        setMineHongtaoBet();
                    } else if (color.equals("C")) {
                        Mine_C = Mine_C + currentBet;
                        setMineCaohuaBet();
                    } else if (color.equals("D")) {
                        Mine_D = Mine_D + currentBet;
                        setMineFangkuaiBet();
                    } else if (color.equals("O")) {
                        Mine_E = Mine_E + currentBet;
                        setMineKingBet();
                    }

                    balance -= currentBet;

                    EventBus.getDefault().post(
                            new CallbackEvent(
                                    Constant.EVENT_NOTIFY_CURRENT_MINE_BET, ""));
                } else if (id == 4) {
                    LogUtil.getLogger().d2("bethaha  id = " + id + "<---response_message-->" + response);
                    // 加值
                    Gson gson = new Gson();
                    ValueData valueData = gson.fromJson(response, ValueData.class);
                    if (!TextUtils.isEmpty(valueData.getMsg())) {
                        Toast.makeText(mContext, valueData.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    ValueItem item = valueData.getResult();
                    balance = (int) item.getMesaScore();

                    EventBus.getDefault().post(
                            new CallbackEvent(
                                    Constant.EVENT_NOTIFY_CURRENT_MINE_BET, ""));
                } else if (id == 6) {
                    // 取消本次押分
                    LogUtil.getLogger().d("bethaha  id = " + id + "<-cancel--response_message-->" + response);
                    balance += getMineBetAll();
                    clearMineBet();
                    EventBus.getDefault().post(
                            new CallbackEvent(
                                    Constant.EVENT_NOTIFY_CURRENT_MINE_BET, ""));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
//	private Map<String, Integer> betMapTemp;
//	private void clearBetMapTemp() {
//		if (betMapTemp == null)
//			betMapTemp = new HashMap<String, Integer>();
//		betMapTemp.clear();
//		betMapTemp.put(KEY_HEITAO, 0);
//		betMapTemp.put(KEY_HONGTAO, 0);
//		betMapTemp.put(KEY_CAOHUA, 0);
//		betMapTemp.put(KEY_FANGKUAI, 0);
//		betMapTemp.put(KEY_KING, 0);
//	}
//	@Override
//	public void onClick(View v) {
//		synchronized (this) {
//			if (!isHighlightEnabled)
//				return;
//			// 余额小于step，没法押注，包括保存也不能
//			if (balance < step) {
//				Toast.makeText(mContext, "余额不足，请充值", Toast.LENGTH_SHORT).show();
//				return;
//			}
//			int A = betMapTemp.get(KEY_HEITAO) + betMapActual.get(KEY_HEITAO);
//			int B = betMapTemp.get(KEY_HONGTAO) + betMapActual.get(KEY_HONGTAO);
//			int C = betMapTemp.get(KEY_CAOHUA) + betMapActual.get(KEY_CAOHUA);
//			int D = betMapTemp.get(KEY_FANGKUAI) + betMapActual.get(KEY_FANGKUAI);
//			int E = betMapTemp.get(KEY_KING) + betMapActual.get(KEY_KING);
//
//			Log.e("onClick-A-before", "betMapTemp:" + betMapTemp.get(KEY_HEITAO) + "------betMapActual:" + betMapActual.get(KEY_HEITAO));
//			Log.e("onClick-B-before", "betMapTemp:" + betMapTemp.get(KEY_HONGTAO) + "------betMapActual:" + betMapActual.get(KEY_HONGTAO));
//			Log.e("onClick-C-before", "betMapTemp:" + betMapTemp.get(KEY_CAOHUA) + "------betMapActual:" + betMapActual.get(KEY_CAOHUA));
//			Log.e("onClick-D-before", "betMapTemp:" + betMapTemp.get(KEY_FANGKUAI) + "------betMapActual:" + betMapActual.get(KEY_FANGKUAI));
//			Log.e("onClick-E-before", "betMapTemp:" + betMapTemp.get(KEY_KING) + "------betMapActual:" + betMapActual.get(KEY_KING));
//			int currentStep = 0;
//			switch (v.getId()) {
//				case R.id.bet_heitao_panel:
//					int tempA = A;
//					A += step;
//					if (!isValidHeitao(A, B, C, D)) {
//						//A = (Constant.FOUR_RED_LIMIT + B + C + D) / 3;
//					}
//					currentStep = A - tempA;
//					Log.e("onClick-A", "tempA = " + tempA + " <A=" + A + " <step=" + step + " <currentStep=" + currentStep);
//					if (currentStep < 0)
//						currentStep = 0;
//					recordBetBeforeConfirm(KEY_HEITAO, currentStep);
//					break;
//				case R.id.bet_hongtao_panel:
//					int tempB = B;
//					B += step;
//					if (!isValidHongtao(A, B, C, D)) {
//						//B = (Constant.FOUR_RED_LIMIT + A + C + D) / 3;
//					}
//					currentStep = B - tempB;
//					if (currentStep < 0)
//						currentStep = 0;
//					recordBetBeforeConfirm(KEY_HONGTAO, currentStep);
//					break;
//				case R.id.bet_caohua_panel:
//					int temp_C = C;
//					C += step;
//					if (!isValidCaohua(A, B, C, D)) {
//						//C = (int)(Constant.FOUR_RED_LIMIT + A + B + D) / 3;
//					}
//					currentStep = C - temp_C;
//					if (currentStep < 0)
//						currentStep = 0;
//					recordBetBeforeConfirm(KEY_CAOHUA, currentStep);
//					break;
//				case R.id.bet_fangkuai_panel:
//					int temp_D = D;
//					D += step;
//					if (!isValidFangkuai(A, B, C, D)) {
//						//D = (Constant.FOUR_RED_LIMIT + A + B + C) / 3;
//					}
//					currentStep = D - temp_D;
//					if (currentStep < 0)
//						currentStep = 0;
//					recordBetBeforeConfirm(KEY_FANGKUAI, currentStep);
//					break;
//				case R.id.bet_king_panel:
//					int temp_E = E;
//					E += step;
//					if (!isValidKing(E)) {
//						//E = Constant.KING_RED_LIMIT;
//					}
//					currentStep = E - temp_E;
//					if (currentStep < 0)
//						currentStep = 0;
//					recordBetBeforeConfirm(KEY_KING, currentStep);
//					break;
//			}
//			// stepBet(currentStep);
////			if(currentStep < 0)
////				currentStep = 0;
//
//			Log.e("onClick-A-after", "betMapTemp:" + betMapTemp.get(KEY_HEITAO) + "------betMapActual:" + betMapActual.get(KEY_HEITAO));
//			Log.e("onClick-B-after", "betMapTemp:" + betMapTemp.get(KEY_HONGTAO) + "------betMapActual:" + betMapActual.get(KEY_HONGTAO));
//			Log.e("onClick-C-after", "betMapTemp:" + betMapTemp.get(KEY_CAOHUA) + "------betMapActual:" + betMapActual.get(KEY_CAOHUA));
//			Log.e("onClick-D-after", "betMapTemp:" + betMapTemp.get(KEY_FANGKUAI) + "------betMapActual:" + betMapActual.get(KEY_FANGKUAI));
//			Log.e("onClick-E-after", "betMapTemp:" + betMapTemp.get(KEY_KING) + "------betMapActual:" + betMapActual.get(KEY_KING));
//
//
//			Log.e("info", "currentStep:" + currentStep + ",balance:" + balance);
////			balance -= currentStep;
//			//涉及精度问题
//			BigDecimal b1 = new BigDecimal(Float.toString(balance));
//			BigDecimal b2 = new BigDecimal(Integer.toString(currentStep));
//			balance = b1.subtract(b2).floatValue();
//			Log.d("info", "balance after:" + balance);
//
//			setMineBet();
//			//EventBus.getDefault().post(new CallbackEvent(Constant.EVENT_NOTIFY_CURRENT_MINE_BET, ""));
//			EventBus.getDefault().post(new CallbackEvent(Constant.EVENT_NOTIFY_PREPARE_TO_BET, ""));
//		}
//	}

    private void initHandler() {

        handler2 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case 1:
                        if (isStop) {
                            LogUtil.getLogger().d7("handler2", "-----3-------handler2---------------");
//                            visibleAll(2, false);
                        } else {
                            LogUtil.getLogger().d7("handler2", "-----1-------handler2---------------");
                            visibleAll(2, false);
                        }
                        break;
                    case 2:
                        LogUtil.getLogger().d7("handler2", "--------2----handler2---------------");
//                        if (!isStop) {

                        visibleAll(1, true);
//                        }else{
//                            visibleAll(5, 1);
//                        }
                        break;
                }
            }
        };
    }

    private void visibleAll(int what, boolean isShow) {
        mHeitaoGuang.setVisibility(View.INVISIBLE);
        mHongtaoGuang.setVisibility(View.INVISIBLE);
        mCaohuaGuang.setVisibility(View.INVISIBLE);
        mFangkuaiGuang.setVisibility(View.INVISIBLE);
        mKingGuang.setVisibility(View.INVISIBLE);
        Message msg = new Message();
        msg.what = what;
        if (isShow) {
            switch (mViewIndex) {
                case 0:
                    mHeitaoGuang.setVisibility(View.VISIBLE);
//                handler2.sendMessageDelayed(msg, 500);
                    break;
                case 1:
                    mHongtaoGuang.setVisibility(View.VISIBLE);
//                handler2.sendMessageDelayed(msg, 500);
                    break;
                case 2:
                    mCaohuaGuang.setVisibility(View.VISIBLE);
//                handler2.sendMessageDelayed(msg, 500);
                    break;
                case 3:
                    mFangkuaiGuang.setVisibility(View.VISIBLE);
//                handler2.sendMessageDelayed(msg, 500);
                    break;
                case 4:
                    mKingGuang.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    break;
                default:
                    break;
            }
        }
        handler2.sendMessageDelayed(msg, 500);
    }

    /**
     * 清除集合中的花色
     */
    private void removeSendMap(String huaSe) {
        sendHsMap.remove(huaSe);
//        Toast.makeText(mContext, "移除花色==" + huaSe, Toast.LENGTH_SHORT).show();
    }

    /**
     * 加入花色押分，待有返回结果时再处理
     */
    private void addSendMap(String huaSe) {
        sendHsMap.put(huaSe, huaSe);
    }

    /**
     * 判断花色是否已经发送过
     *
     * @param huaSe 当前点击的花色
     * @return false:没有发送过,true:已经发送过一次，正在等待服务返回
     */
    private boolean isExistHuase(String huaSe) {
        if (!TextUtils.isEmpty(sendHsMap.get(huaSe))) {
            LogUtil.getLogger().d7("07281000", "存在的花色=" + huaSe);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 状态切换后清空上次的押分集合，便于下次押分
     */
    public void cleanSendMap() {
        sendHsMap.clear();
    }
}
